import pymysql
import redis
from elasticsearch_dsl.connections import connections
from flask_sqlalchemy import SQLAlchemy

from shop.conf import es_url, redis_host, redis_port
from shop.model.es_model import SearchWord

pymysql.install_as_MySQLdb()

db = SQLAlchemy()

rds = redis.Redis(host=redis_host, port=redis_port)

# 保存短信验证码的redis
message_redis = redis.Redis(db=1,host=redis_host, port=redis_port)

# 保存用户id和token的redis
token_redis = redis.Redis(db=2,host=redis_host, port=redis_port)


# 连接es
def init_es():
    connections.create_connection(hosts=[es_url])
    SearchWord.init()


# 获取redis的值
def get_pickle_file_path(key_string):
    res_bytes = rds.get(key_string)
    if res_bytes:
        return str(res_bytes.decode())
    else:
        return None


# 设置redis的值
def set_pickle_file_path(key_string, path):
    try:
        rds.set(key_string, path, 60 * 60 * 1)
    except Exception as e:
        print(e)


# 保存手机号和手机验证码到redis中
def save_phone_code(phone, code):
    try:
        message_redis.set(phone, code, 60 * 5)
    except Exception as e:
        print(e)


# 根据手机号获取手机号的验证码
def get_phone_code(phone):
    code = message_redis.get(phone)
    if code:
        return str(code.decode())
    else:
        return None


# 保存用户token
def save_user_token(user_id, token):
    try:
        token_redis.set(token, user_id, 60 * 60 * 24 * 30)
    except Exception as e:
        print(e)


# 验证用户token
def check_user_token(token):
    user_id = token_redis.get(token)
    save_user_token(user_id, token)
    return user_id


# 线程池
from concurrent.futures import ThreadPoolExecutor

pool = ThreadPoolExecutor(3)
